//
//  SLTeenagersModelVC.m
//  BXlive
//
//  Created by sweetloser on 2020/8/17.
//  Copyright © 2020 cat. All rights reserved.
//

#import "SLTeenagersModelVC.h"
#import "SLTeenagerPWDSettingVC.h"
#import <SLDeveloperTools/SLDeveloperTools.h>
#import <Masonry/Masonry.h>
#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>
#import "GradientButton.h"
// WKWebView 内存不释放的问题解决
@interface WeakWebViewScriptMessageDelegate()

@end

@implementation WeakWebViewScriptMessageDelegate

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}

#pragma mark - WKScriptMessageHandler
//遵循WKScriptMessageHandler协议，必须实现如下方法，然后把方法向外传递
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    if ([self.scriptDelegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
        [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
    }
}

@end



@interface SLTeenagersModelVC ()<WKScriptMessageHandler, WKUIDelegate, WKNavigationDelegate>
@property(nonatomic,strong)UIView *navigationView;
@property(nonatomic,strong)UIButton *bottomBtn;

@property(nonatomic,strong)WKWebView *wkWebView;

//网页加载进度视图
@property (nonatomic, strong) UIProgressView * progressView;

@end

@implementation SLTeenagersModelVC

#pragma mark - Getter
- (UIProgressView *)progressView {
    if (!_progressView){
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, __kTopAddHeight + 64, self.view.frame.size.width, 2)];
        _progressView.tintColor = sl_normalColors;
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    [self.view setBackgroundColor:[UIColor sl_colorWithHex:0xFFFFFF]];
    [self setupNavigationView];
    
    [self setupBottomView];
    
    //创建网页配置对象
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
    // 创建设置对象
    WKPreferences *preference = [[WKPreferences alloc]init];
    //最小字体大小 当将javaScriptEnabled属性设置为NO时，可以看到明显的效果
    preference.minimumFontSize = 0;
    //设置是否支持javaScript 默认是支持的
    preference.javaScriptEnabled = YES;
    // 在iOS上默认为NO，表示是否允许不经过用户交互由javaScript自动打开窗口
    preference.javaScriptCanOpenWindowsAutomatically = YES;
    config.preferences = preference;
    
    
    //设置请求的User-Agent信息中应用程序名称 iOS9后可用
    config.applicationNameForUserAgent = @"ChinaDailyForiPad";
    
    //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
    WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
    //这个类主要用来做native与JavaScript的交互管理
    WKUserContentController * wkUController = [[WKUserContentController alloc] init];
    //注册一个name为jsToOcNoPrams的js方法 设置处理接收JS方法的对象
    [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcNoPrams"];
    [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcWithPrams"];
    
    config.userContentController = wkUController;
    
    //以下代码适配文本大小
    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    //用于进行JavaScript注入
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [config.userContentController addUserScript:wkUScript];
    
    _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) configuration:config];
    [self.view addSubview:_wkWebView];
    WS(weakSelf);
    [_wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.navigationView.mas_bottom).offset(2);
        make.left.right.mas_equalTo(0);
        make.bottom.equalTo(weakSelf.bottomBtn.mas_top).offset(__ScaleWidth(-10));
    }];
    // UI代理
    _wkWebView.UIDelegate = self;
    // 导航代理
    _wkWebView.navigationDelegate = self;
    // 是否允许手势左滑返回上一级, 类似导航控制的左滑返回
    _wkWebView.allowsBackForwardNavigationGestures = YES;
    
    NSMutableURLRequest *res = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[BXAppInfo appInfo].teenager_desc_url]];
    [_wkWebView loadRequest:res];
    
    [self.view addSubview:self.progressView];
    
    //添加监测网页加载进度的观察者
    [self.wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
    [self.wkWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
}
-(void)setupNavigationView{
    _navigationView = [UIView new];
    [self.view addSubview:_navigationView];
    [_navigationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(__kTopAddHeight+64);
    }];
    [_navigationView setBackgroundColor:[UIColor sl_colorWithHex:0xFFFFFF]];
    WS(weakSelf);
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn addTarget:self action:@selector(pop) forControlEvents:BtnTouchUpInside];
    [_navigationView addSubview:backBtn];
    [backBtn setImage:CImage(@"back_black") forState:BtnNormal];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.mas_equalTo(0);
        make.width.height.mas_equalTo(44);
    }];
    UILabel *label = [UILabel createLabelWithFrame:CGRectZero BackgroundColor:SLClearColor Text:NSLocalizedString(@"青少年模式", nil) Font:SLBFont(__ScaleWidth(18)) TextColor:sl_textColors];
    label.textAlignment = 1;
    [_navigationView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(44);
        make.right.mas_equalTo(-44);
        make.centerY.equalTo(weakSelf.navigationView.mas_bottom).offset(-22);
        make.height.mas_equalTo(25);
    }];
}
-(void)setupBottomView{
    _bottomBtn = [[GradientButton alloc] initWithFrame:CGRectZero];
    [self.view addSubview:_bottomBtn];
    [_bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(__ScaleWidth(12));
        make.right.mas_equalTo(__ScaleWidth(-12));
        make.bottom.mas_equalTo(__ScaleWidth(-50)+__kBottomAddHeight);
        make.height.mas_equalTo(__ScaleWidth(44));
    }];
    _bottomBtn.layer.masksToBounds = YES;
    _bottomBtn.layer.cornerRadius = __ScaleWidth(22);
    [_bottomBtn setBackgroundColor:sl_normalColors];
    [_bottomBtn setTitle:NSLocalizedString(@"开启青少年模式", nil) forState:BtnNormal];
    [_bottomBtn setTitleColor:sl_whiteTextColors forState:BtnNormal];
    _bottomBtn.titleLabel.font = SLBFont(__ScaleWidth(16));
    [_bottomBtn addTarget:self action:@selector(bottomBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)bottomBtnAction{
    SLTeenagerPWDSettingVC *vc = [[SLTeenagerPWDSettingVC alloc] init];
    [self pushVc:vc];
}

-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                      context:(void *)context{
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
        && object == _wkWebView) {
        
        NSLog(@"网页加载进度 = %f",_wkWebView.estimatedProgress);
        self.progressView.progress = _wkWebView.estimatedProgress;
        if (_wkWebView.estimatedProgress >= 1.0f) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.progress = 0;
            });
        }
        
    }else if([keyPath isEqualToString:@"title"]
             && object == _wkWebView){
        self.navigationItem.title = _wkWebView.title;
    }else{
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
    //用message.body获得JS传出的参数体
    NSDictionary * parameter = message.body;
    NSLog(@"%@",parameter);
    //JS调用OC
    if([message.name isEqualToString:@"jsToOcNoPrams"]){
        
    }else if([message.name isEqualToString:@"jsToOcWithPrams"]){
        
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
